package com.stateflow.facade.common.util;

import com.stateflow.facade.common.template.CommonTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * Created by weiqingming on 2017/2/21.
 * 对象序列化工具类
 */
public class SerializableUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(SerializableUtils.class);

    private static SerializableUtils serializableUtils;

    public static SerializableUtils getUtils() {

        if (serializableUtils == null) {
            synchronized (SerializableUtils.class) {
                serializableUtils = new SerializableUtils();
            }
        }
        return serializableUtils;
    }


    /**
     * 序列化，使用常规java序列化方式
     *
     * @param obj
     * @return
     * @throws Exception
     */

    public <T> byte[] serialize(T obj) {
        ObjectOutputStream out = null;
        StringBuilder s = new StringBuilder();
        s.append("traceId：").append(CommonTemplate.getTraceId());

        try {

            ByteArrayOutputStream os = new ByteArrayOutputStream();

            out = new ObjectOutputStream(os);

            out.writeObject(obj);

            return os.toByteArray();

        } catch (IOException e) {

            LOGGER.error(s.append("IOException").toString(), e);

        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return null;

    }

    /**
     * 反序列化
     *
     * @param by
     * @return
     * @throws Exception
     */

    public <T> T deSerialize(byte[] by) {

        ObjectInputStream in = null;
        StringBuilder s = new StringBuilder();
        s.append("traceId：").append(CommonTemplate.getTraceId());

        try {

            ByteArrayInputStream is = new ByteArrayInputStream(by);

            in = new ObjectInputStream(is);
            return (T) in.readObject();

        } catch (IOException e) {

            LOGGER.error(s.append("IOException").toString(), e);

        } catch (ClassNotFoundException e) {

            LOGGER.error(s.append("ClassNotFoundException").toString(), e);

        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return null;
    }



}
